﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ENG.TeachersDiary.Classes
{
  public class DistinctList<T> : IList<T>
  {
    private List<T> inner = new List<T>();
    public bool RaiseExceptionOnDistinctInsert { get; set; }


    public int IndexOf(T item)
    {
      return inner.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
      if (this.Contains(item))
        if (RaiseExceptionOnDistinctInsert)
          throw new DuplicateItemException(item);
        else
          return;
      else
        inner.Insert(index, item);
    }

    public void RemoveAt(int index)
    {
      inner.RemoveAt(index);
    }

    public T this[int index]
    {
      get
      {
        return inner[index];
      }
      set
      {
        for (int i = 0; i < this.Count; i++)
        {
          if (inner[i].Equals(value) && i != index)
          {
            if (RaiseExceptionOnDistinctInsert)
              throw new DuplicateItemException(value);
            else
              return;
          }
        }

        inner[index] = value;
      }
    }

    public void Add(T item)
    {
      if (this.Contains(item))
        if (RaiseExceptionOnDistinctInsert)
          throw new DuplicateItemException(item);
        else
          return;
      else
        inner.Add(item);      
    }

    public void Clear()
    {
      inner.Clear();
    }

    public bool Contains(T item)
    {
      return inner.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
      throw new NotImplementedException();
    }

    public int Count
    {
      get { return inner.Count; }
    }

    public bool IsReadOnly
    {
      get { return false; }
    }

    public bool Remove(T item)
    {
      return inner.Remove(item);
    }

    public IEnumerator<T> GetEnumerator()
    {
      return inner.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return inner.GetEnumerator();
    }
  }
}
